import { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Scroll, Send, ArrowLeft, Menu, X, Sun, Moon } from 'lucide-react';
import { useTheme } from '../hooks/useTheme';
import { toast } from 'sonner';

// 三国历史人物类型定义
type Character = 'liuBei' | 'caoCao' | 'sunQuan';

// 检查后端服务是否可用的工具函数
const checkBackendHealth = async (retries: number = 2, delay: number = 500): Promise<boolean> => {
  try {
    const response = await fetch('http://localhost:5000/api/health', {
      timeout: 2000
    });

    if (!response.ok && retries > 0) {
      console.warn(`后端服务检查失败，将重试(${retries}次剩余)...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return checkBackendHealth(retries - 1, delay * 2);
    }

    return response.ok;
  } catch (error) {
    console.error('后端服务不可用:', error);

    // 如果还有重试次数，进行重试
    if (retries > 0) {
      console.warn(`请求异常，将重试(${retries}次剩余)...`);
      await new Promise(resolve => setTimeout(resolve, delay));
      return checkBackendHealth(retries - 1, delay * 2);
    }

    return false;
  }
};

// 对话消息类型定义
interface Message {
  id: string;
  content: string;
  sender: 'user' | Character;
  timestamp: Date;
  isFromApi?: boolean; // 是否来自真实API
  isMock?: boolean; // 是否是模拟回复
  apiError?: string; // API错误信息
}

// 人物信息配置
const characterConfig = {
  liuBei: {
    name: '刘备',
    color: 'bg-red-600',
    bgColor: 'bg-red-50 dark:bg-red-950',
    borderColor: 'border-red-200 dark:border-red-800',
    avatarUrl: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=Chinese%20Three%20Kingdoms%20period%20hero%20Liu%20Bei%2C%20ancient%20Chinese%20warrior%2C%20historical%20figure&sign=571c86a4426369e57797e4599c3af40c',
    description: '刘备（161年－223年），字玄德，东汉末年幽州涿郡涿县人，三国时期蜀汉开国皇帝。',
  },
  caoCao: {
    name: '曹操',
    color: 'bg-yellow-600',
    bgColor: 'bg-yellow-50 dark:bg-yellow-950',
    borderColor: 'border-yellow-200 dark:border-yellow-800',
    avatarUrl: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=Chinese%20Three%20Kingdoms%20period%20hero%20Cao%20Cao%2C%20ancient%20Chinese%20warlord%2C%20historical%20figure&sign=0024977ff2c669e8940649b8629f4267',
    description: '曹操（155年－220年），字孟德，东汉末年杰出的政治家、军事家、文学家、书法家。',
  },
  sunQuan: {
    name: '孙权',
    color: 'bg-blue-600',
    bgColor: 'bg-blue-50 dark:bg-blue-950',
    borderColor: 'border-blue-200 dark:border-blue-800',
    avatarUrl: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=Chinese%20Three%20Kingdoms%20period%20hero%20Sun%20Quan%2C%20ancient%20Chinese%20emperor%2C%20historical%20figure&sign=572e99c9bb3a6e384e14d2e882f83849',
    description: '孙权（182年－252年），字仲谋，吴郡富春人，三国时期孙吴的建立者。',
  },
};

// Mock AI回复数据
const mockResponses: Record<string, string[]> = {
  liuBei: [
    '备乃中山靖王之后，汉景帝阁下玄孙。',
    '吾与云长、翼德桃园结义，誓同生死。',
    '三顾茅庐，方得卧龙先生相助。',
    '以人为本，此乃为君之道。',
    '勿以恶小而为之，勿以善小而不为。',
    '汉室倾颓，奸臣窃命，备不量力，欲伸大义于天下。',
    '孤之有孔明，犹鱼之有水也。',
    '夫济大事必以人为本，今人归吾，吾何忍弃去！',
  ],
  caoCao: [
    '宁可我负天下人，休教天下人负我。',
    '设使国家无有孤，不知当几人称帝，几人称王。',
    '老骥伏枥，志在千里；烈士暮年，壮心不已。',
    '夫英雄者，胸怀大志，腹有良谋，有包藏宇宙之机，吞吐天地之志者也。',
    '何以解忧？唯有杜康。',
    '对酒当歌，人生几何！',
    '我持此槊，破黄巾，擒吕布，灭袁术，收袁绍，深入塞北，直抵辽东，纵横天下。',
    '青青子衿，悠悠我心。但为君故，沉吟至今。',
  ],
  sunQuan: [
    '天下英雄，唯使君与操耳，本初之徒，不足数也。',
    '孤承父兄余业，思有桓文之功。',
    '能用众力，则无敌于天下矣；能用众智，则无畏于圣人矣。',
    '孤与老贼，势不两立。',
    '士别三日，即更刮目相待。',
    '夫存不忘亡，安必虑危，古之善教。',
    '孤非周公瑾，不帝矣。',
    '诸将吏敢复有言当迎操者，与此案同！',
  ],
};

export default function Home() {
  const { theme, toggleTheme, isDark } = useTheme();
  const [selectedCharacter, setSelectedCharacter] = useState<Character | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [typing, setTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // 从后端API获取AI回复
  useEffect(() => {
    if (messages.length > 0 && messages[messages.length - 1].sender === 'user' && selectedCharacter) {
      const lastMessage = messages[messages.length - 1];

      const fetchAIResponse = async () => {
        let configData: any = null; // 在函数顶部声明configData，使其在整个函数作用域内可用

        try {
          // 设置为正在输入状态
          setTyping(true);

          console.log(`正在向后端请求${selectedCharacter}的回复...`);

          // 检查后端服务是否可用（使用增强版检查函数）
          const isBackendAvailable = await checkBackendHealth(2, 500);
          if (!isBackendAvailable) {
            throw new Error('后端服务未启动或不可用');
          }

          // 获取配置状态（增强版，带重试机制）
          try {
            console.log('正在检查API配置状态...');

            // 为避免缓存问题，添加时间戳参数
            const timestamp = new Date().getTime();
            // 确保使用正确的接口路径
            const configResponse = await fetch(`http://localhost:5000/api/config/status?t=${timestamp}`);

            if (!configResponse.ok) {
              // 详细的错误信息
              console.error(`配置检查请求失败: ${configResponse.status} ${configResponse.statusText}`);
              throw new Error(`配置检查请求失败: ${configResponse.status} ${configResponse.statusText}`);
            }

            // 安全处理配置响应
            configData = await configResponse.json();
            console.log('API配置状态:', configData);

            // 检查是否配置了当前人物的API密钥
            const hasApiKey = configData?.keyStatus?.[selectedCharacter] === 'configured';
            const apiBaseUrlValid = configData?.hasValidBaseUrl === true;

            // 提供更详细的配置状态信息
            let statusInfo = [];
            if (!hasApiKey) {
              statusInfo.push(`${characterConfig[selectedCharacter].name}的API密钥未配置或使用默认值`);
            } else {
              statusInfo.push(`${characterConfig[selectedCharacter].name}的API密钥已配置`);
            }

            if (!apiBaseUrlValid) {
              statusInfo.push('API基础URL未配置或使用默认值');
            } else {
              statusInfo.push(`API基础URL: ${configData?.apiBaseUrl || '未配置'}`);
            }

            console.log('配置状态详情:', statusInfo.join(' | '));

            // 只有在确实需要提示用户时才显示toast
            if (!hasApiKey || !apiBaseUrlValid) {
              // 只显示一次提示，避免重复提示
              if (messages.length <= 1) { // 只有第一条用户消息时显示
                toast(statusInfo.join('，') + '。将使用模拟回复', {
                  duration: 5000,
                  description: "请在server/.env文件中配置KIMI_API_KEY来使用Kimi大模型",
                  type: 'warning'
                });
              }
            } else {
              // 配置正确时也给用户一个反馈
              console.log(`${characterConfig[selectedCharacter].name}的API配置看起来正确，将尝试使用Kimi大模型`);
            }
          } catch (configError) {
            console.error('获取配置状态失败:', configError);
            // 错误处理，避免因为配置检查失败而影响整个对话流程
            // 提供更友好的错误信息和解决方案
            let errorMessage = `配置检查失败: ${configError.message}`;
            let solution = "将使用模拟回复继续对话";

            // 根据错误类型提供更具体的解决方案
            if (configError.message.includes('404')) {
              solution = "请确认后端服务已启动，或尝试使用模拟回复";
            } else if (configError.message.includes('NetworkError')) {
              solution = "请检查网络连接，确保后端服务正在运行";
            }

            toast(errorMessage, {
              duration: 7000,
              type: 'warning',
              description: solution
            });

            // 即使配置检查失败，也继续使用应用
            configData = {
              keyStatus: {
                [selectedCharacter]: 'missing'
              },
              hasValidBaseUrl: false
            };
          }



          // 安全处理API响应
          let data;
          try {
            // 先发送请求获取响应
            const response = await fetch('http://localhost:5000/api/chat/message', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                character: selectedCharacter,
                userMessage: lastMessage.content
              })
            });

            try {
              data = await response.json();
            } catch (jsonError) {
              // 处理JSON解析错误（通常是HTML响应）
              console.error('JSON解析错误，可能是API返回了HTML:', jsonError);

              // 读取响应文本以确定错误类型
              const responseText = await response.text();
              console.log('API响应内容:', responseText.substring(0, 200) + '...');

              // 创建友好的错误消息
              const friendlyError = responseText.includes('DOCTYPE')
                  ? 'API返回了HTML内容，可能是服务器错误'
                  : 'API返回格式错误，无法解析';

              throw new Error(friendlyError);
            }
          } catch (error) {
          }

          console.log('后端回复:', data);

          if (data.success) {
            // 安全地从配置数据中获取API密钥状态
            const hasApiKey = configData?.keyStatus?.[selectedCharacter] === 'configured';

            setMessages(prevMessages => [...prevMessages, {
              id: Date.now().toString(),
              content: data.response,
              sender: selectedCharacter,
              timestamp: new Date(),
              isFromApi: true,
              isMock: !hasApiKey
            }]);
          } else {
            toast('获取回复失败，请重试');

            // 失败时使用备用的mock回复
            const responses = mockResponses[selectedCharacter];
            const randomResponse = responses[Math.floor(Math.random() * responses.length)];

            setTimeout(() => {
              setMessages(prevMessages => [...prevMessages, {
                id: Date.now().toString(),
                content: randomResponse,
                sender: selectedCharacter,
                timestamp: new Date(),
                isMock: true
              }]);
            }, 1000);
          }
        } catch (error) {
          console.error('获取AI回复失败:', error.message);

          // 创建用户友好的错误消息
          let userErrorMessage = '获取回复失败';
          if (error.message.includes('DOCTYPE') || error.message.includes('HTML')) {
            userErrorMessage = '后端服务未启动或不可用';
          } else if (error.message.includes('404')) {
            userErrorMessage = '请求的资源不存在';
          } else if (error.message.includes('ECONNREFUSED')) {
            userErrorMessage = '无法连接到后端服务';
          } else {
            userErrorMessage = `获取回复失败: ${error.message}`;
          }

          // 只在特定情况下显示toast，避免过多提示
          if (messages.length <= 2) {
            toast(userErrorMessage, {
              duration: 5000,
              type: 'warning',
              description: "将使用内置模拟回复功能，请检查Kimi API密钥配置"
            });
          }

          // 失败时使用备用的mock回复
          const responses = mockResponses[selectedCharacter];
          const randomResponse = responses[Math.floor(Math.random() * responses.length)];

          setTimeout(() => {
            setMessages(prevMessages => [...prevMessages, {
              id: Date.now().toString(),
              content: randomResponse,
              sender: selectedCharacter,
              timestamp: new Date(),
              isMock: true,
              apiError: error.message
            }]);
          }, 800);
        } finally {
          // 无论成功失败，都设置为不在输入状态
          setTyping(false);
        }
      };

      fetchAIResponse();
    }
  }, [messages, selectedCharacter]);

  // 发送消息
  const handleSendMessage = () => {
    if (!inputMessage.trim() || !selectedCharacter) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      content: inputMessage.trim(),
      sender: 'user',
      timestamp: new Date(),
    };

    setMessages(prevMessages => [...prevMessages, newMessage]);
    setInputMessage('');
  };

  // 选择历史人物
  const handleCharacterSelect = (character: Character) => {
    setSelectedCharacter(character);
    setMessages([]);
    setIsMenuOpen(false);

    // 检查后端服务状态
    checkBackendHealth().then(isAvailable => {
      if (!isAvailable) {
        toast('后端服务未启动，将使用内置模拟回复', {
          description: '您可以继续对话，推荐使用: npm run dev:server-vanilla 启动无依赖后端服务',
          duration: 5000,
          type: 'warning'
        });
      }
    });

    // 添加欢迎消息
    setMessages([{
      id: Date.now().toString(),
      content: `在下${characterConfig[character].name}，请问有何指教？`,
      sender: character,
      timestamp: new Date(),
    }]);

    toast(`现在正在与${characterConfig[character].name}对话`);
  };

  // 返回人物选择
  const handleBackToSelection = () => {
    setSelectedCharacter(null);
    setMessages([]);
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 渲染人物选择界面
  const renderCharacterSelection = () => (
      <div className="flex flex-col h-full">
        {/* 顶部标题栏 */}
        <header className="p-4 border-b border-gray-200 dark:border-gray-800 flex justify-between items-center">
          <h1 className="text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-red-600 via-yellow-500 to-blue-600">
            三国风云对话
          </h1>
          <button
              onClick={toggleTheme}
              className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
              aria-label="Toggle theme"
          >
            {isDark ? <Sun size={20} /> : <Moon size={20} />}
          </button>
        </header>

        {/* 主内容区 */}
        <main className="flex-1 flex flex-col items-center justify-center p-6">
          <motion.h2
              className="text-3xl font-bold mb-8 text-center"
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5 }}
          >
            与三国英雄对话
          </motion.h2>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 w-full max-w-4xl">
            {(['liuBei', 'caoCao', 'sunQuan'] as Character[]).map((character) => (
                <motion.div
                    key={character}
                    className={`rounded-2xl overflow-hidden border ${characterConfig[character].borderColor} shadow-lg cursor-pointer transition-all hover:shadow-xl dark:shadow-2xl`}
                    whileHover={{ scale: 1.03, y: -5 }}
                    whileTap={{ scale: 0.98 }}
                    onClick={() => handleCharacterSelect(character)}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5, delay: ['liuBei', 'caoCao', 'sunQuan'].indexOf(character) * 0.2 }}
                >
                  <div className={`h-2 ${characterConfig[character].color}`}></div>
                  <div className={`p-6 ${characterConfig[character].bgColor}`}>
                    <div className="flex justify-center mb-4">
                      <div className="w-24 h-24 rounded-full overflow-hidden border-4 border-white dark:border-gray-800 shadow-md">
                        <img
                            src={characterConfig[character].avatarUrl}
                            alt={characterConfig[character].name}
                            className="w-full h-full object-cover"
                        />
                      </div>
                    </div>
                    <h3 className="text-xl font-bold text-center mb-2">{characterConfig[character].name}</h3>
                    <p className="text-sm text-gray-600 dark:text-gray-400 text-center">{characterConfig[character].description}</p>
                  </div>
                </motion.div>
            ))}
          </div>
        </main>

        {/* 页脚 */}
        <footer className="p-4 text-center text-sm text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-800">
          <p>三国历史AI问答系统 © {new Date().getFullYear()}</p>
        </footer>
      </div>
  );

  // 渲染聊天界面
  const renderChatInterface = () => {
    if (!selectedCharacter) return null;

    const config = characterConfig[selectedCharacter];

    return (
        <div className="flex flex-col h-full">
          {/* 聊天头部 */}
          <header className={`p-4 border-b ${config.borderColor} flex items-center`}>
            <button
                onClick={handleBackToSelection}
                className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors mr-3"
                aria-label="Back to selection"
            >
              <ArrowLeft size={20} />
            </button>
            <div className="flex items-center">
              <div className="w-10 h-10 rounded-full overflow-hidden mr-3">
                <img
                    src={config.avatarUrl}
                    alt={config.name}
                    className="w-full h-full object-cover"
                />
              </div>
              <div>
                <h2 className="font-bold">{config.name}</h2>
                <p className="text-xs text-gray-500 dark:text-gray-400">在线</p>
              </div>
            </div>
            <div className="ml-auto flex items-center gap-2">
              <button
                  onClick={toggleTheme}
                  className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
                  aria-label="Toggle theme"
              >
                {isDark ? <Sun size={20} /> : <Moon size={20} />}
              </button>
              <button
                  onClick={() => setIsMenuOpen(!isMenuOpen)}
                  className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors md:hidden"
                  aria-label="Open menu"
              >
                {isMenuOpen ? <X size={20} /> : <Menu size={20} />}
              </button>
            </div>
          </header>

          {/* 侧边菜单 - 移动端 */}
          <AnimatePresence>
            {isMenuOpen && (
                <motion.div
                    className={`fixed inset-0 bg-black bg-opacity-50 z-50 md:hidden ${config.bgColor}`}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    onClick={() => setIsMenuOpen(false)}
                >
                  <motion.div
                      className={`absolute right-0 top-0 bottom-0 w-64 ${config.bgColor} p-4 overflow-y-auto`}
                      initial={{ x: '100%' }}
                      animate={{ x: 0 }}
                      exit={{ x: '100%' }}
                      transition={{ type: 'spring', bounce: 0, duration: 0.4 }}
                      onClick={(e) => e.stopPropagation()}
                  >
                    <h3 className="font-bold mb-4">切换人物</h3>
                    {(['liuBei', 'caoCao', 'sunQuan'] as Character[]).map((character) => (
                        <div
                            key={character}
                            className={`flex items-center p-3 mb-2 rounded-lg cursor-pointer ${
                                selectedCharacter === character
                                    ? `${characterConfig[character].color} text-white`
                                    : 'hover:bg-gray-100 dark:hover:bg-gray-800'
                            }`}
                            onClick={() => handleCharacterSelect(character)}
                        >
                          <div className="w-8 h-8 rounded-full overflow-hidden mr-3">
                            <img
                                src={characterConfig[character].avatarUrl}
                                alt={characterConfig[character].name}
                                className="w-full h-full object-cover"
                            />
                          </div>
                          <span>{characterConfig[character].name}</span>
                        </div>
                    ))}
                  </motion.div>
                </motion.div>
            )}
          </AnimatePresence>

          {/* 聊天内容区 */}
          <main className="flex-1 flex overflow-hidden">
            {/* 侧边栏 - 桌面端 */}
            <div className={`hidden md:block w-64 border-r ${config.borderColor} p-4 overflow-y-auto`}>
              <h3 className="font-bold mb-4">切换人物</h3>
              {(['liuBei', 'caoCao', 'sunQuan'] as Character[]).map((character) => (
                  <div
                      key={character}
                      className={`flex items-center p-3 mb-2 rounded-lg cursor-pointer transition-colors ${
                          selectedCharacter === character
                              ? `${characterConfig[character].color} text-white`
                              : 'hover:bg-gray-100 dark:hover:bg-gray-800'
                      }`}
                      onClick={() => handleCharacterSelect(character)}
                  >
                    <div className="w-8 h-8 rounded-full overflow-hidden mr-3">
                      <img
                          src={characterConfig[character].avatarUrl}
                          alt={characterConfig[character].name}
                          className="w-full h-full object-cover"
                      />
                    </div>
                    <span>{characterConfig[character].name}</span>
                  </div>
              ))}
            </div>

            {/* 消息列表 */}
            <div className={`flex-1 overflow-y-auto p-4 ${config.bgColor} bg-opacity-50`}>
              <div className="max-w-3xl mx-auto">
                {messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full py-16">
                      <Scroll size={48} className="text-gray-400 mb-4" />
                      <p className="text-gray-500 dark:text-gray-400">暂无消息，开始对话吧！</p>
                    </div>
                ) : (
                    messages.map((message) => (
                        <motion.div
                            key={message.id}
                            className={`flex mb-4 ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
                            initial={{ opacity: 0, y: 20 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ duration: 0.3 }}
                        >
                          {message.sender !== 'user' && (
                              <div className="w-8 h-8 rounded-full overflow-hidden mr-2 flex-shrink-0">
                                <img
                                    src={characterConfig[message.sender as Character].avatarUrl}
                                    alt={characterConfig[message.sender as Character].name}
                                    className="w-full h-full object-cover"
                                />
                              </div>
                          )}
                          <div
                              className={`max-w-[80%] p-3 rounded-2xl shadow-sm ${
                                  message.sender === 'user'
                                      ? 'bg-blue-500 text-white rounded-br-none'
                                      : `${characterConfig[message.sender as Character].borderColor} bg-white dark:bg-gray-800 rounded-bl-none`
                              } ${message.isFromApi ? 'ring-1 ring-blue-400 dark:ring-blue-600' : ''} ${message.apiError ? 'ring-1 ring-amber-400 dark:ring-amber-600' : ''}`}
                          >
                            <p className="whitespace-pre-wrap">{message.content}</p>
                            <p className={`text-xs mt-1 ${message.sender === 'user' ? 'text-blue-200' : 'text-gray-400'}`}>
                              {message.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                              {message.isFromApi ? ' · AI' : ''}
                              {message.isMock ? ' · 模拟回复' : ''}
                            </p>
                          </div>
                        </motion.div>
                    ))
                )}
                {typing && (
                    <div className="flex justify-start mb-4">
                      <div className="w-8 h-8 rounded-full overflow-hidden mr-2 flex-shrink-0">
                        {selectedCharacter && (
                            <img
                                src={characterConfig[selectedCharacter].avatarUrl}
                                alt={characterConfig[selectedCharacter].name}
                                className="w-full h-full object-cover"
                            />
                        )}
                      </div>
                      <div className={`max-w-[20%] p-3 rounded-2xl shadow-sm ${
                          selectedCharacter ? characterConfig[selectedCharacter].borderColor : 'border-gray-200 dark:border-gray-700'
                      } bg-white dark:bg-gray-800 rounded-bl-none flex items-center justify-center space-x-1`}>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }}></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }}></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }}></div>
                      </div>
                    </div>
                )}
                <div ref={messagesEndRef} />
              </div>
            </div>
          </main>

          {/* 消息输入区 */}
          <footer className={`p-4 border-t ${config.borderColor}`}>
            <div className="max-w-3xl mx-auto flex items-center">
              <div className="flex-1 border rounded-full overflow-hidden flex items-center">
                <input
                    type="text"
                    value={inputMessage}
                    onChange={(e) => setInputMessage(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder={`与${config.name}对话...`}
                    className="flex-1 p-3 bg-transparent outline-none"
                />
              </div>
              <button
                  onClick={handleSendMessage}
                  className={`ml-2 p-3 rounded-full ${config.color} text-white shadow-md hover:shadow-lg transition-all`}
                  disabled={!inputMessage.trim()}
                  aria-label="Send message"
              >
                <Send size={20} />
              </button>
            </div>
          </footer>
        </div>
    );
  };

  return (
      <div className={`min-h-screen flex flex-col ${isDark ? 'dark bg-gray-900 text-white' : 'bg-white text-gray-900'} transition-colors duration-300`}>
        {selectedCharacter ? renderChatInterface() : renderCharacterSelection()}
      </div>
  );
}